# -*- coding: utf-8 -*-

from hashlib import sha256

from django.core.cache import cache
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe

from djmarkitup import fields, settings
from djmarkitup.renderers import DJMIU_MARKUP_RENDERERS


_get_key = lambda s: sha256(s.encode('utf-8')).hexdigest()


class DjMarkItUpBase(models.Model):
    markup_language = fields.DjMarkupSelectField(_(u'Markup Language'))
    markup_text = fields.DjMarkItUpField(_(u'Markup Text'), blank=True)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if self.markup_text and settings.DJMIU_USE_CACHE:
            # Call _get_redered to save rendered markup to cache
            self._get_rendered()
        super(DjMarkItUpBase, self).save(*args, **kwargs)

    def get_rendered_markup(self, **options):
        return mark_safe(self._get_rendered(**options))

    def _get_rendered(self, **options):
        if not self.markup_text:
            return u''
        if settings.DJMIU_USE_CACHE:
            key = _get_key(self.markup_text)
            rendered = cache.get(key)
            if rendered is not None:
                return rendered
        render_func = DJMIU_MARKUP_RENDERERS[self.markup_language]
        rendered = render_func(self.markup_text, **options)
        if settings.DJMIU_USE_CACHE:
            cache.set(key, rendered, 60 * 60 * 24)
        return rendered
